package cn.tedu.csmall.securitytest4;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.junit.jupiter.api.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class jwt {
    String secretKey = "dascxzvSFDGFHaggasMasgfgmcxz";
    @Test
    void testjwt(){
        Map<String ,Object> claim = new HashMap<>();
        claim.put("id",123);
        claim.put("username","zy");

      String Jwt = Jwts.builder()
              //声明算法与数据类型
              .setHeaderParam("alg","HS256")
              .setHeaderParam("typ","JWT")
              //Payload: 数据，表现为claim
              .setClaims(claim)
              .setExpiration(new Date(System.currentTimeMillis()+2*60*1000))
              //验证签名
              .signWith(SignatureAlgorithm.HS256,secretKey)
              .compact();
        System.out.println(Jwt);
    }


    @Test
    void parse(){
        String jwt = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6MTIzLCJleHAiOjE2NzgyNDM2MTMsInVzZXJuYW1lIjoienkifQ.07KeoH4PWqeO-eURhHR0YAU3cVEh8q4Ud7P66lLQHE8";
        Claims claims = Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
        Object id = claims.get("id");
        Object username = claims.get("username");
        System.out.println("id: "+id);
        System.out.println("username: "+username);
    }
}
